﻿//var app = angular.module('WebApp', ['ipCookie']);

var app = angular.module('WebApp', ['ngFileUpload', 'ipCookie']);

app.filter("JSONDate", function ($filter) {
    return function (input, format) {
        if (input) {
            var r = input.replace(/[^0-9|-]+/g, '');
            var timestamp = Number(r);
            return $filter("date")(timestamp, format);
        }
        else {
            return input;
        }
    }
});

app.directive("ngTouchstart", function () {
    return {
        controller: ["$scope", "$element", function ($scope, $element) {

            $element.bind("touchstart", onTouchStart);
            function onTouchStart(event) {
                var method = $element.attr("ng-touchstart");
                $scope.$apply(method);
            }

        }]
    }
})
app.directive("ngTouchmove", function () {
    return {
        controller: ["$scope", "$element", function ($scope, $element) {

            $element.bind("touchstart", onTouchStart);
            function onTouchStart(event) {
                event.preventDefault();
                $element.bind("touchmove", onTouchMove);
                $element.bind("touchend", onTouchEnd);
            }
            function onTouchMove(event) {
                var method = $element.attr("ng-touchmove");
                $scope.$apply(method);
            }
            function onTouchEnd(event) {
                event.preventDefault();
                $element.unbind("touchmove", onTouchMove);
                $element.unbind("touchend", onTouchEnd);
            }

        }]
    }
})
app.directive("ngTouchend", function () {
    return {
        controller: ["$scope", "$element", function ($scope, $element) {

            $element.bind("touchend", onTouchEnd);
            function onTouchEnd(event) {
                var method = $element.attr("ng-touchend");
                $scope.$apply(method);
            }

        }]
    }
})
app.directive("ngTap", function () {
    return {
        controller: ["$scope", "$element", function ($scope, $element) {

            $element.bind("tap", onTouchEnd);
            function onTouchEnd(event) {
                var method = $element.attr("ng-tap");
                $scope.$apply(method);
            }

        }]
    }
})
app.filter("HiddenText", function ($filter) {
    return function (text) {
        if (text.length > 20) {
            return text.substring(0, 22) + "......"
        }
        else {
            return input;
        }
    }
});
app.value('option', {
    date: {
        format: 'L',
        toolbarPlacement: 'bottom',
        showTodayButton: true,
        showClear: true,
        showClose: true,
        ignoreReadonly: true,
        locale: 'zh-cn'
    },
    datetime: {
        format: 'L HH:mm:ss',
        sideBySide: true,
        toolbarPlacement: 'bottom',
        showTodayButton: true,
        showClear: true,
        showClose: true,
        ignoreReadonly: true,
        locale: 'zh-cn'
    }
});
/* 自定义缓存服务 **/
app.factory('cache', function ($cacheFactory) {

    var service = {};
    var cache = $cacheFactory('myCache');

    service.get = function (key) {
        return cache.get(key);
    }

    service.put = function (key, value) {
        cache.put(key, value);
    }

    return service;
});
app.factory('common', function ($window) {
    var service = {};

    service.error = function ($scope) {
        $scope.result.code = -1;
        $scope.result.message = "服务器访问失败，请重新刷新界面";
    }

    service.success = function ($scope, returnUrl, ret) {
        if (ret.Code == 100 && returnUrl != null) {
            $window.location.href = "../.." + returnUrl;
        }
        $scope.result.code = ret.Code;
        $scope.result.message = ret.Message;
        if (ret.Data && ret.Data.CurrentPageIndex) {
            $scope.result.currentPage = ret.Data.CurrentPageIndex;
            $scope.result.pageSize = ret.Data.PageSize;
            $scope.result.totalPage = ret.Data.TotalPageCount;
            $scope.result.pages = ret.Data.Pages;
            $scope.result.totalItemCount = ret.Data.TotalItemCount;
        }
    }

    service.addUrlParamVal = function (url, key, value) {
        if (/\?/g.test(url)) {
            var pattern = new RegExp(key + '=([^&]*)');
            if (url.match(pattern)) {
                var tmp = '/(' + key + '=)([^&]*)/gi';
                url = url.replace(eval(tmp), key + "=" + value);
            } else {
                url += "&" + key + "=" + value;
            }
        }
        else {
            url += "?" + key + "=" + value;
        }

        return url;
    }

    service.removeUrlParamVal = function (url, key) {
        if (/\?/g.test(url)) {
            var pattern = new RegExp(key + '=([^&]*)');
            if (url.match(pattern)) {
                var tmp = '/(&?' + key + '=)([^&]*)/gi';
                url = url.replace(eval(tmp), "");
            }
        }

        return url;
    }

    return service;
});

app.controller('MainController', function ($scope, $http, $window, cache, ipCookie) {
    var account = sessionStorage.getItem('AccountInfo');

    if (account == null || account == "") {
        $http({
            method: 'POST',
            url: '../Account/GetAccountInfo'
        })
            .success(function (ret) {
                if (ret.Code == 100) {
                    $scope.User = ret.Data;
                    sessionStorage.setItem("AccountInfo", JSON.stringify(ret.Data));
                    var now = getNow();
                    //watermark({ "watermark_txt": $scope.User.UserNo+" "+ now, "watermark_fontsize": '9px' });
                }
                else {
                     alert(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
            });

        //$scope.UnreadMsg = [];
        //$http({
        //    method: 'POST',
        //    url: '../Account/GetUnreadMessage'
        //})
        //    .success(function (ret) {
        //        if (ret.Code == 100) {
        //            $scope.UnreadMsg = ret.Data;
        //        }
        //    })
    }
    else {
        $scope.User = JSON.parse(account);
    }

    if (!cache.get("routes")) {
        $http.get("../Bussiness/js/nav-route.json").success(function (json) {
            cache.put("routes", json);
            $scope.init();
        }).error(function (data, status, headers, config) { });
    } else {
        $scope.init();
    }

    $scope.init = function () {
        var routes = cache.get("routes");
        $scope.firstLevel = {}
        $scope.secondLevel = {}


        var path = $window.location.pathname;
        if (path == "/") path = "/GeneratorSet/GeneratorSetList";
        if (path == "/Admin") path = "/Admin/Index";
        var contrast = routes[path];
        $scope.ControllerName = routes[path]?.first;


        //console.log($scope.ControllerName+"-"+routes[path].second);
        //$scope.firstLevel[contrast["first"]] = true;
        //$scope.secondLevel[contrast["second"]] = true;
        //console.log($scope.firstLevel);
    };

    $scope.doLogout = function () {
        //var valid = confirm("确认退出?");
        //if (valid) {
        //    $http.post('../Account/Logout')
        //        .success(function (ret) {
        //            document.cookie == "";
        //            $window.location.href = $window.location.href;
        //        })
        //        .error(function (data, status, headers, config) {

        //        });
        //}

        alertify.okBtn("确认")
            .cancelBtn("取消").confirm("确认退出当前账号？", function (ev) {
                ev.preventDefault();

                $http.post('../Account/Logout')
                    .success(function (ret) {
                        sessionStorage.removeItem("AccountInfo");
                        sessionStorage.removeItem("LeftMenu");
                        $window.location.href = $window.location.href;
                    })
                    .error(function (data, status, headers, config) {

                    });

            }, function (ev) {
                ev.preventDefault();
            });
    }

    $scope.GetLeftMenu = function () {
        var menu = sessionStorage.getItem('LeftMenu');
        if (menu == null || menu == "") {
            $http({
                method: 'POST',
                url: '../Account/GetLeftMenu'
            })
                .success(function (ret) {
                    if (ret.Code == 100) {
                        $scope.MenuList = ret.Data;
                        sessionStorage.setItem("LeftMenu", JSON.stringify(ret.Data));
                    }
                    else {
                        alert(ret.Msg);
                    }
                })
                .error(function (data, status, headers, config) {
                });
        }
        else {
            $scope.MenuList = JSON.parse(menu);
        }
    }

    $scope.MenuGroupList = function (menulist) {
        $scope.MainMenuList = [];
        $scope.FormMenuList = [];
        $scope.SettingMenuList = [];
        for (var i = 0; i < menulist.length; i++) {
            if (menulist[i].Group == 'Main') {
                $scope.MainMenuList.push(menulist[i]);
            }
            else if (menulist[i].Group == 'HiddenTrouble') {
                $scope.FormMenuList.push(menulist[i]);
            }
            else if (menulist[i].Group == 'Organization') {
                $scope.SettingMenuList.push(menulist[i]);
            }
        }
    }

    $scope.CheckPermission = function (module, action) {
        setTimeout(function () {
            var isshow = false;
            var rolelist = $scope.User.RoleList;
            for (var i = 0; i < rolelist.length; i++) {
                if (module == rolelist[i].ModuleName) {
                    if (action == 'Add') {
                        isshow = rolelist[i].IsAdd;
                    }
                    else if (action == 'View') {
                        isshow = rolelist[i].IsView;
                    }
                    else if (action == 'Modify') {
                        isshow = rolelist[i].IsModify;
                    }
                    else if (action == 'Delete') {
                        isshow = rolelist[i].IsDelete;
                    }
                }
            }
            return isshow;
        }, 2000);

    }


    $scope.AlertBox = function (text) {
        new PNotify({
            title: '系统提示',
            text: text,
            type: 'success',
            styling: 'fontawesome'
        });
    }

    $scope.GoPageCallBack = function (page, returnurl) {
        location.href = page + "&pagename=" + urlencode(returnurl);
    }


    function urlencode(str) {
        str = (str + '').toString();
        return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
    }



});
